package com.yf.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

@Log4j2
public class SendEmail {
    private static final String SEND_CLOUD_KEY = "fe3958dc9305304dbf4d62970ed3455a";
    private static final String SEND_CLOUD_USER = "sc_0vaeos_test_J5IwuW";
    private static final String url = "https://api.sendcloud.net/apiv2/mail/send";
    private static final HttpClient httpclient = HttpClientBuilder.create().build();

    public static boolean sendEmail(String receiver, String subject, String content) throws IOException {
        HttpPost httPost = new HttpPost(url);
        List<BasicNameValuePair> params = new ArrayList<>();
        // 您需要登录SendCloud创建API_USER，使用API_USER和API_KEY才可以进行邮件的发送。
        params.add(new BasicNameValuePair("apiUser", SEND_CLOUD_USER));
        params.add(new BasicNameValuePair("apiKey", SEND_CLOUD_KEY));
        params.add(new BasicNameValuePair("from", "service@sendcloud.im"));
        params.add(new BasicNameValuePair("fromName", "408刷题小网站"));
        params.add(new BasicNameValuePair("to", receiver));
        params.add(new BasicNameValuePair("subject", subject));
        params.add(new BasicNameValuePair("html", content));

        httPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        // 请求
        HttpResponse response = httpclient.execute(httPost);
        // 处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
            // 读取xml文档
            String result = EntityUtils.toString(response.getEntity());
            log.info(String.format("receiver: %s send email result: %s", receiver, result));
            return true;
        } else {
            log.error(String.format("receiver: %s send email failed.", receiver));
        }
        httPost.releaseConnection();
        return false;
    }
}
